﻿using MvcBoard.Domain.Abstract;
using MvcBoard.Domain.Entities;
using MvcBoard.WebUI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcBoard.WebUI.Controllers
{
    public class BoardController : Controller
    {
        public int PageSize = 4;
        private IMvcBoardRepository repository;

        public BoardController(IMvcBoardRepository repo)
        {
            repository = repo;
        }
        //
        // GET: /Board/

        public ViewResult List(string title , int page = 1)
        {
            BoardListViewModel viewModel = new BoardListViewModel
            {
                Boards = repository.Boards
                .Where(p => title == null || p.Title.Contains(title))
                .OrderBy(p => p.BoardID)
                .Skip((page - 1) * PageSize)
                .Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = title == null ? repository.Boards.Count() : repository.Boards.Where(p => p.Title.Contains(title)).Count()
                }
            };

            return View(viewModel);
        }

        public ViewResult View(int board_idx)
        {
            Board board = repository.Boards.Where(p => p.BoardID == board_idx).FirstOrDefault();

            if (board == null)
            {
                return View("List");
            }
            else
            {
                return View(board);
            }
        }

        public ActionResult Delete(int boardid)
        {
            Board board = repository.Boards.Where(p => p.BoardID == boardid).FirstOrDefault();

            if (board != null)
            {
                repository.DeleteBoard(board);
                TempData["message"] = "정상적으로 삭제되었습니다.";
            }

            return RedirectToAction("List");
        }

        public ViewResult Create()
        {
            return View("Edit", new Board());
        }

        public ViewResult Edit(int boardid)
        {
            Board board = repository.Boards.Where(p => p.BoardID == boardid).FirstOrDefault();

            return View(board);
        }

        [HttpPost]
        public ActionResult Edit(Board board)
        {
            if (board.BoardID == 0)
            {
                board.Regid = "evenute";
            }
            if (ModelState.IsValid)
            {
                repository.SaveBoard(board);
                TempData["message"] = string.Format("게시글이 수정되었습니다.");
                return RedirectToAction("List");
            }
            else
            {
                return View(board);
            }
        }
    }
}
